var template = require('./template');
var sv = function (setting) {
    //当前页面对象
    var $page = setting.page || $('body'),
    //翻页参数
        page = {
            pageIndex: 1,
            pageSize: 15
        },
    //滚动容器
        content = $page,
    //是否加载
        isLoad = true,
    //当前页面数据
        pageData;
    //初始化方法
    (function init() {
        $(window).on('scroll',function () {
            if ($(this).scrollTop() > 0 &&
                ($(this).scrollTop() + $(window).height()) >= ( $page.height() - 50)
                && isLoad) {
                refresh();
            }
        });
        $page.find('.append-loading').append("<div class='live-loading'>" +
            "<i class='img'></i>正在加载，请稍后... </div>" +
            "<div class='live-error hide'>获取数据失败</div>");
    })();
    //刷新方法
    function refresh() {
        if (isLoad == false) return;
        isLoad = false;
        $page.find('.live-error').addClass('hide');
        $ajax({
            url: setting.url,
            data: $.extend({
                page: page
            }, typeof setting.data == 'function' ? setting.data() : setting.data),
            success: function (data) {
                if (!pageData) {
                    pageData = data.result[setting.dataKey];
                } else if (!!pageData.data) {
                    pageData = pageData.concat(data.result[setting.dataKey]);
                }
                if (!!setting.beforeComplete) data.attach = setting.beforeComplete(data.attach);
                $page.find('#' + setting.viewId).parent()[0].innerHTML += template(setting.viewId, {data: data.result[setting.dataKey]});
                if (!!setting.reload)setting.reload(data);
                $page.find('#' + setting.viewId).triggerHandler('reload', [data]);
                page=data.result.page;
                isLoad = page.pageIndex*1<page.pages*1;
                page.pageIndex=page.pageIndex*1+1+"";
            },
            error: function (data) {
                if (data.resultCode != '0' && !!data.resultMsg) {
                    $.alert(data.resultMsg);
                }
                console.log(data);
                $page.find('.live-loading').addClass('hide');
                $page.find('.live-error').removeClass('hide');
                isLoad = false;
            }
        });
    }

    refresh();
    return {
        //重置view数据
        reset: function (callback) {
            if (!callback)callback = function () {
                $page.find('.scroll-view-data').remove();
                $page.find('.live-loading').removeClass('hide');
                refresh();
            }
            pageData = undefined;
            isLoad = true;
            callback();
        },
        getData: function () {
            return pageData;
        }
    }
};
module.exports = sv;